import React from 'react'
import style from './style.tree'
import cx from 'classnames'
import Link from '../link'

export
function walk(node, _id, cb, map) {
  const { id='id',  children='children' } = map
  if (node[children]) {
    return {
      ...node,
      [children]: node[children].map(item => {
        if (item[id] === _id) {
          return {
            ...item,
            [children]: cb(item[children]) || []
          }
        } else {
          return walk(item, _id, cb, map)
        }
      })
    }
  }
  return node
}


class Node extends React.Component {

  handleClick() {
    const { handler } = this.props
    handler && handler()
  }

  constructor(props) {
    super(props)
    const { map = {} } = props
    this.name = map.name || 'name'
    this.children = map.children || 'children'
  }

  render() {
    return (
      <li>
        <Link 
          icon="arrow"
          iconRotate="-90"
          onClick={() => this.props.toggle(this.props)} 
          label={ this.props[this.name] }
        />
        {
          this.props.children?
          <List data={this.props[this.children]}/>
          : null
        }
      </li>
    )
  }
}

class List extends React.Component {
  render() {
    return (
      <ul>
        { 
          this.props.data.map((item, i) => (
            <Node key={i} {...item}/>
          )) 
        }
      </ul>
    )
  }
}

export default ({ root, className, ...others }) => (
  <ul className={cx({
    [style.root]: true,
    [className]: className
  })}>
    <Node {...root} {...others}/>
  </ul>
)
